<?php

class PublishAction extends CAction
{
    private function renderView($succ, $recipe)
    {
        if(!$succ){
            foreach($recipe->getErrors() as $errors) {
                foreach($errors as $error) {
                    if($error!='')
                        $errorContent.="$error\n";
                }
            }
        }
        else {
            $redirectUrl=CHtml::normalizeUrl(array('list','id'=>$recipe->userId));
        }
    
        $this->controller->renderPartial('/common/json',array(
            'data'=>array(
                'succ'=>$succ,
                'error'=>$errorContent,
                'redirectUrl'=>$redirectUrl,
        )));    
    }
    
    private function validate(&$recipe)
    {
        $recipe->scenario='publish';    
        $recipe->validate();
        
        $stepEmpty=true;
        $steps=Step::loadObjectsByRecipeId($recipe->id);
        foreach($steps as $step){
            if($step->memo!==''){
                $stepEmpty=false;
                break;
            }
        }
        
        if($stepEmpty)
            $recipe->addError('steps', $recipe->getAttributeLabel('steps').' 不能为空');
        
        return !$recipe->hasErrors();
    }

    public function run()
    {
        if(!Yii::app()->request->isPostRequest || !isset($_POST['id']))
            throw new CHttpException(400,'the request is invalid');
                
        $recipe=Recipe::loadObjectById($_POST['id']);
        if($recipe===null)
            throw new CHttpException(404,'The requested recipe does not exist.');
        if($recipe->userId!=Yii::app()->user->id)
            throw new CHttpException(403,'cannot edit the recipe not belong to you');
        if($recipe->status!=Recipe::$statusEnum['draft']){
            throw new CHttpException(403,'recipe cannot publish. status='.$object->status);
        }

        if(!$this->validate($recipe)){
            $this->renderView(false,$recipe);
        }
        else {
            $succ=Recipe::publish($recipe);
            $this->renderView($succ,$recipe);
        }
    }
}

?>
